package org.leetcode.middle.leetcode146;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LRUCache2 {

    class Node{
        int key,val;
        Node prev,next;
        Node(int key,int val){
            this.val=val;
            this.key=key;
        }
    }

    //虚拟节点
    private final int capacity;
    Node dummy = new Node(0,0);
    Map<Integer,Node> map = new HashMap<>();

    public LRUCache2(int capacity) {
        this.capacity=capacity;
        dummy.next=dummy;
        dummy.prev=dummy;
    }

    public int get(int key) {
        Node node = getNode(key);
        return node==null ? -1 :node.val;
    }

    public void put(int key, int value) {

        Node node = getNode(key);
        if (node!=null){
            node.val=value;
            return;
        }

        Node newNode = new Node(key,value);
        map.put(key,newNode);
        putHead(newNode);

        if (map.size()>capacity){
            Node removeNode = dummy.prev;
            remove(removeNode);
            map.remove(removeNode.key);
        }

    }

    private Node getNode(int key){
        //没有当前的元素
        if (!map.containsKey(key)){
            return null;
        }

        Node curNode = map.get(key);
        //先移除
        remove(curNode);
        //再放到链表的首部
        putHead(curNode);
        return curNode;
    }

    //将当前的元素移除
    private void remove(Node node){
        node.prev.next=node.next;
        node.next.prev=node.prev;
    }

    //将元素放到链表的首部
    private void putHead(Node node){

        node.prev=dummy;
        node.next=dummy.next;

        dummy.next=node;
        node.next.prev=node;
    }


}
